<template>
  <div class="exam-room-container">
    <h2>考场布置</h2>

    <!-- 课程号搜索框 -->
    <div class="search-course">
      <h3>按课程号查询考试安排</h3>
      <div class="search-input-container">
        <input v-model="courseId" type="text" placeholder="请输入课程号" />
        <button @click="searchExams">搜索</button>
      </div>
    </div>

    <!-- 学生查看考试安排 -->
    <div class="view-exams">
      <h3>查看考试安排</h3>
      <!-- 显示提示信息 -->
      <p v-if="examList.length === 0 && courseId.trim() === ''">当前暂无考试</p>
      <p v-if="examList.length === 0 && courseId.trim() !== ''">未找到该课程的考试安排</p>

      <!-- 表格显示考试安排 -->
      <table v-else class="exam-table">
        <thead>
          <tr>
            <th>考试时间</th>
            <th>考场号</th>
            <th>课程名称</th>
            <th>课程号</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="exam in examList" :key="exam.examTime">
            <td>{{ formatDate(exam.examTime) }}</td>
            <td>{{ exam.roomNumber }}</td>
            <td>{{ exam.courseName }}</td>
            <td>{{ exam.courseId }}</td>
            <td>
              <button @click="openSubmitQuestionDialog(exam.courseId)">
                提交题目
              </button>
            </td>
          </tr>
        </tbody>
      </table>
    </div>

    <!-- 提交题目模态框 -->
    <el-dialog
      :visible.sync="showSubmitDialog"
      title="提交题目"
      width="50%"
    >
      <el-form :model="submitForm">
        <el-form-item label="选择文件">
          <input type="file" @change="handleFileUpload" />
        </el-form-item>
        <el-form-item label="题目ID">
          <el-input v-model="submitForm.questionId" placeholder="请输入题目ID" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="showSubmitDialog = false">取消</el-button>
        <el-button type="primary" @click="submitQuestion">提交</el-button>
      </span>
    </el-dialog>

    <!-- 提交结果模态框 -->
    <el-dialog
      :visible.sync="showResultDialog"
      title="提交结果"
      width="50%"
    >
      <p v-if="submissionResult">{{ submissionResult }}</p>
      <p v-else>正在加载...</p>
      <span slot="footer" class="dialog-footer">
        <el-button @click="showResultDialog = false">关闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import axios from "axios";

export default {
  name: "ExamRoomSetup",
  data() {
    return {
      studentId: null, // 存储学生ID
      examList: [], // 存储学生的考试安排
      courseId: "", // 存储输入的课程号
      showSubmitDialog: false, // 控制提交题目模态框的显示
      showResultDialog: false, // 控制提交结果模态框的显示
      submissionResult: "", // 存储提交结果
      submitForm: {
        file: null, // 文件对象
        questionId: "", // 题目ID
      },
    };
  },
  mounted() {
    this.studentId = this.$store.state.status.userId; // 获取当前学生的ID
    if (this.studentId) {
      this.fetchExamList(this.studentId); // 获取该学生的考试安排
    } else {
      console.error("未获取到学生ID");
    }
  },
  watch: {
    // 监听 courseId 的变化，当 courseId 为空时，重新查询所有考试安排
    courseId(newValue) {
      if (newValue.trim() === "") {
        this.fetchExamList(this.studentId); // 如果搜索框为空，查询所有考试安排
      }
    },
  },
  methods: {
    fetchExamList(studentId) {
      axios
        .get("http://localhost:8085/exam/studentlist", {
          params: { studentId },
        })
        .then((response) => {
          this.examList = response.data;
        })
        .catch((error) => {
          console.error("获取考试安排失败:", error);
        });
    },

    searchExams() {
      if (this.courseId.trim()) {
        this.fetchExamListByCourseId(this.studentId, this.courseId); // 按课程号查询
      } else {
        this.fetchExamList(this.studentId); // 查询所有考试安排
      }
    },

    fetchExamListByCourseId(studentId, courseId) {
      axios
        .get("http://localhost:8085/exam/studentlistbycourseid", {
          params: { studentId, courseId },
        })
        .then((response) => {
          this.examList = response.data;
        })
        .catch((error) => {
          console.error("获取考试安排失败:", error);
        });
    },

    formatDate(dateString) {
      const date = new Date(dateString);
      const options = {
        year: "numeric",
        month: "long",
        day: "numeric",
        hour: "2-digit",
        minute: "2-digit",
      };
      return date.toLocaleString("zh-CN", options); // 格式化考试时间
    },

    openSubmitQuestionDialog(courseId) {
      this.showSubmitDialog = true; // 显示模态框
      this.submitForm.file = null; // 清空之前的文件
      this.submitForm.questionId = ""; // 清空题目ID
    },

    handleFileUpload(event) {
      this.submitForm.file = event.target.files[0]; // 获取上传的文件
    },

    submitQuestion() {
      if (!this.submitForm.file || !this.submitForm.questionId) {
        this.$message.error("文件和题目ID不能为空！");
        return;
      }

      const formData = new FormData();
      formData.append("file", this.submitForm.file); // 添加文件
      formData.append("questionId", this.submitForm.questionId); // 添加题目ID

      axios
        .post("http://localhost:8085/exam/uploadpaper", formData, {
          headers: {
            "Content-Type": "multipart/form-data",
          },
        })
        .then((response) => {
          // 显示返回结果
          this.submissionResult = response.data.result; // 假设返回的数据中包含 `result`
          this.showSubmitDialog = false; // 关闭提交模态框
          this.showResultDialog = true; // 打开结果模态框
        })
        .catch((error) => {
          console.error("提交题目失败:", error);
          this.$message.error("提交题目失败，请稍后再试！");
        });
    },
  },
};
</script>

<style scoped>
/* 样式部分保持不变，与之前代码一致 */
.exam-room-container {
  padding: 20px;
  border: 1px solid #ddd;
  border-radius: 10px;
  background-color: #fafafa;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  max-width: 900px;
  margin: 30px auto;
}

h2 {
  font-size: 28px;
  font-weight: bold;
  color: #333;
  text-align: center;
}

.search-course {
  margin-bottom: 20px;
}

h3 {
  font-size: 24px;
  color: #555;
  margin-bottom: 10px;
}

.search-input-container {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 20px;
}

input[type="text"] {
  padding: 10px;
  font-size: 16px;
  width: 70%;
  max-width: 350px;
  margin-right: 10px;
  border: 1px solid #ddd;
  border-radius: 5px;
}

button {
  padding: 10px 20px;
  font-size: 16px;
  border: none;
  background-color: #007BFF;
  color: white;
  cursor: pointer;
  border-radius: 5px;
}

button:hover {
  background-color: #0056b3;
}

.view-exams {
  margin-top: 20px;
}

p {
  font-size: 18px;
  color: #888;
  text-align: center;
}

.exam-table {
  width: 100%;
  border-collapse: collapse;
  margin-top: 20px;
  background-color: #fff;
}

.exam-table th,
.exam-table td {
  padding: 12px;
  text-align: center;
  border: 1px solid #ddd;
}

.exam-table th {
  background-color: #f4f4f4;
  font-size: 18px;
}

.exam-table td {
  font-size: 16px;
}

.exam-table tr:nth-child(even) {
  background-color: #f9f9f9;
}

.paper-content p {
  margin-bottom: 10px;
  font-size: 16px;
  line-height: 1.5;
}

@media (max-width: 768px) {
  .search-input-container {
    flex-direction: column;
    align-items: stretch;
  }
  input[type="text"],
  button {
    width: 100%;
    margin-right: 0;
  }
}
</style>
